package news.tencent.charco.android.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import news.tencent.charco.android.R;
import news.tencent.charco.android.base.BaseFragment;
import news.tencent.charco.android.entity.NewsEs;
import news.tencent.charco.android.mimc.MimcServer;
import news.tencent.charco.android.mimc.Msg;
import news.tencent.charco.android.mimc.MsgData;
import news.tencent.charco.android.mimc.MsgHandleInterface;
import news.tencent.charco.android.utils.DbOperateUtil;
import news.tencent.charco.android.utils.ToastUtil;
import news.tencent.charco.android.utils.UIUtils;
import news.tencent.charco.android.view.activity.MainActivity;
import news.tencent.charco.android.view.activity.WebViewActivity;
import news.tencent.charco.android.view.adapter.BaseFragmentAdapter;
import news.tencent.charco.android.view.adapter.SearchAdapter;
import news.tencent.charco.android.view.adapter.SearchResultAdapter;
import news.tencent.charco.android.widget.SearchRecyclerView;
import news.tencent.charco.android.widget.XEditText;
import news.tencent.charco.android.widget.magicindicator.MagicIndicator;
import news.tencent.charco.android.widget.magicindicator.buildins.UIUtil;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.CommonNavigator;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import news.tencent.charco.android.widget.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView;

import static news.tencent.charco.android.view.fragment.NewsListFragment.ADMIN_DETAIL;

/**
 * Created 18/7/5 11:09
 * Author:charcolee
 * Version:V1.0
 * ----------------------------------------------------
 * 文件描述：
 * ----------------------------------------------------
 */

public class NewsFragment extends BaseFragment implements MsgHandleInterface,View.OnClickListener, BaseQuickAdapter.OnItemClickListener {

    public static final int offset = 100;

    public final int KEYWORD_SEARCH = 20;

    /**
     * 新闻详情
     */
    public static final int SEARCH_DETAIL = 40;

    /**
     * 关键字搜索服务员
     */
    public static final String ADMIN_KEYWORDS_SEARCH = "AdminKeywordsSearch0829";

    private ViewPager mViewPager;
    private MainActivity mMainActivity;
    private View mLltNews;
    private DrawerLayout mDrawerLayout;
    private List<BaseFragment> fragments = new ArrayList<>();
    private MagicIndicator mIndicator;
    private String[] channels;
    private SearchRecyclerView mSearchRecyclerView;
    private SearchAdapter mSearchAdapter;
    private SearchResultAdapter mResultAdapter;
    private int mDisplayWidth;
    private XEditText mEditSearch;
    private ProgressBar mResultProgress;

    private List<NewsEs> newsEsList = new ArrayList<>();
    private List<String> keywordList = new ArrayList<>();

    ResultHandler resultHandler = new ResultHandler(this);

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_news;
    }

    @Override
    public void initView(View rootView) {
        mViewPager = findViewById(R.id.viewpager);
        mIndicator = findViewById(R.id.magic_indicator);
        mDrawerLayout = findViewById(R.id.drawer_layout);
        mLltNews = findViewById(R.id.llt_news);
        //设置搜索界面宽度为屏幕宽度
        mDisplayWidth = getResources().getDisplayMetrics().widthPixels;
        LinearLayout mLltSearch = rootView.findViewById(R.id.llt_search);
        ViewGroup.LayoutParams layoutParams = mLltSearch.getLayoutParams();
        layoutParams.width = mDisplayWidth;
        mLltSearch.setLayoutParams(layoutParams);
        mSearchRecyclerView = findViewById(R.id.recyclerView);
        mSearchRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        DbOperateUtil dbOperateUtil = DbOperateUtil.getInstance();
        keywordList = dbOperateUtil.getAllKeywords();
        mSearchAdapter = new SearchAdapter(keywordList);
        mSearchRecyclerView.setAdapter(mSearchAdapter);
        mSearchAdapter.setOnItemClickListener(this);

        mResultAdapter = new SearchResultAdapter(newsEsList);
        mResultAdapter.setOnItemClickListener(this);

        mEditSearch = findViewById(R.id.et_search);
        mResultProgress = findViewById(R.id.result_progress);

        MimcServer mimcServer =  MimcServer.getInstance();
        mimcServer.addMsgHandle(this);
    }

    //获取arrays.xml中存放的数据
    @Override
    protected void loadData() {
        channels = getResources().getStringArray(R.array.channel);
        initIndicator();
//        for (String channel : channels){
//            fragments.add(new NewsListFragment());
//        }
        fragments.add(NewsListFragment.newInstance("EastMoney", 0));
        fragments.add(NewsListFragment.newInstance("EastMoney", 1));
        fragments.add(NewsListFragment.newInstance("EastMoney", 2));
        fragments.add(NewsListFragment.newInstance("EastMoney", 3));
        mViewPager.setAdapter(new BaseFragmentAdapter(fragments, getChildFragmentManager()));
    }

    @Override
    public void initListener() {
        findViewById(R.id.tv_seacher).setOnClickListener(this);
        findViewById(R.id.tv_close_search).setOnClickListener(this);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //position为0的时候才能打开搜索界面
                if (position == 0) {
                    unlockDrawer();
                } else {
                    lockDrawer();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mIndicator.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                mIndicator.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                mIndicator.onPageScrollStateChanged(state);
            }
        });
        mDrawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                mLltNews.scrollTo((int) (-mDisplayWidth * slideOffset * 0.8), 0);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                mMainActivity.hideBottomBarLayout();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mMainActivity.showBottomBarLayout();
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        mEditSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
                // TODO Auto-generated method stub
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    String keywords = textView.getText().toString();
                    keywordSearch(keywords);
                }
                return false;
            }

        });

        mEditSearch.setOnXTextChangeListener(new XEditText.OnXTextChangeListener(){
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after){
                System.out.println("before");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count){
                System.out.println("ing");
            }

            @Override
            public void afterTextChanged(Editable s){
                System.out.println("after");
            }
        });
        mEditSearch.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View v, boolean hasFocus){
                if (hasFocus){
                    System.out.println("focus");
                    mSearchRecyclerView.setAdapter(mSearchAdapter);
                    mSearchAdapter.notifyDataSetChanged();
                }else {
                    System.out.println("rlease focus");
                    mSearchRecyclerView.setAdapter(mResultAdapter);
                }
            }
        });

    }

    private void keywordSearch(String keywords) {
        Msg msg = new Msg();
        msg.setKeywords(keywords);
        msg.setPageFrom(0);
        msg.setPageSize(50);
        msg.setSubType(KEYWORD_SEARCH);

        try {
            MimcServer mimcServer = MimcServer.getInstance();
            mimcServer.sendMessage(ADMIN_KEYWORDS_SEARCH, msg);
            newsEsList.clear();
            mSearchRecyclerView.setAdapter(mResultAdapter);

            DbOperateUtil dbOperateUtil = DbOperateUtil.getInstance();
            if (keywordList.contains(keywords)){
                keywordList.remove(keywords);
                dbOperateUtil.deleteKeyword(keywords);
            }
            keywordList.add(0,keywords);
            dbOperateUtil.saveKeyword(keywords);
            mSearchAdapter.notifyDataSetChanged();
            hideSoftInput();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initIndicator() {
        CommonNavigator mCommonNavigator = new CommonNavigator(UIUtils.getContext());
        mCommonNavigator.setSkimOver(true);
        mCommonNavigator.setAdapter(new CommonNavigatorAdapter() {

            //顶头列表放入
            @Override
            public int getCount() {
                return channels.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ClipPagerTitleView clipPagerTitleView = new ClipPagerTitleView(context);
                clipPagerTitleView.setText(channels[index]);
                clipPagerTitleView.setTextSize(UIUtils.sp2px(15));
                clipPagerTitleView.setClipColor(getResources().getColor(R.color.colorPrimary));
                clipPagerTitleView.setTextColor(getResources().getColor(R.color.color_BDBDBD));
                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setYOffset(UIUtil.dip2px(context, 3));
                indicator.setRoundRadius(5);
                indicator.setColors(getResources().getColor(R.color.colorPrimary));
                return indicator;
            }
        });
        mIndicator.setNavigator(mCommonNavigator);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) getActivity();
    }

    private void lockDrawer() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    private void unlockDrawer() {
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

    public boolean isSeacherOpen() {
        return mDrawerLayout.isDrawerOpen(Gravity.START);
    }

    public void closeSeacher() {
        mDrawerLayout.closeDrawer(Gravity.START);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_seacher:
                mResultProgress.setProgress(0);
                mEditSearch.setTextToSeparate("");
                mDrawerLayout.openDrawer(Gravity.START);
                break;
            case R.id.tv_close_search:
                mDrawerLayout.closeDrawer(Gravity.START);
                mSearchRecyclerView.setAdapter(mSearchAdapter);
                mResultProgress.setProgress(0);
                hideSoftInput();
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof SearchAdapter){
            ToastUtil.showToast(mSearchAdapter.getItem(position));
            mEditSearch.setTextToSeparate(mSearchAdapter.getItem(position));
            mEditSearch.clearFocus();
            keywordSearch(mSearchAdapter.getItem(position));
        }else if (adapter instanceof SearchResultAdapter){
            NewsEs newsEs = mResultAdapter.getItem(position);
            ToastUtil.showToast(newsEs.getNewsEsSource().getDigest());

            Msg msg = new Msg();
            msg.setSubType(SEARCH_DETAIL);
            msg.setNewsId(newsEs.getNewsEsSource().getNid());
            try {
                MimcServer mimcServer =  MimcServer.getInstance();
                mimcServer.sendMessage(ADMIN_DETAIL, msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void hideSoftInput(){
        InputMethodManager imm = (InputMethodManager) this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null){
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 单聊消息回调
     */
    @Override
    public void handleMsg(MsgData msgData){
        if (null == msgData) {
            return;
        }

        if (msgData.getSubType() == SEARCH_DETAIL){
            if(msgData.getTotal().equals(0)){
                ToastUtil.showToast("无详情");
                return;
            }
            Message message = new Message();
            message.what = 200;
            message.obj = msgData;
            resultHandler.sendMessage(message);
            return;
        }

        if (null != msgData.getSubType() && msgData.getSubType() == KEYWORD_SEARCH){
            if(msgData.getTotal().equals(0)){
                ToastUtil.showToast("无结果");
                return;
            }
            //去重
            NewsEs newsEs = new NewsEs();
            newsEs.setNewsEsSource(msgData);
            if (newsEsList.contains(newsEs)){
                return;
            }

            newsEsList.add(newsEs);
            Collections.sort(newsEsList, new Comparator<NewsEs>() {
                @Override
                public int compare(NewsEs u1, NewsEs u2) {
                    long diff = u1.getNewsEsSource().getIndexTime() - u2.getNewsEsSource().getIndexTime();
                    if (diff > 0) {
                        return -1;
                    }else if (diff < 0) {
                        return 1;
                    }
                    return 0; //相等为0
                }
            });

            if (msgData.getTotal() > 0){
                Message message = new Message();
                double index = newsEsList.size();
                double total = msgData.getTotal();
                message.what = (int)((index / total) * 100);
                if (index > total){
                    message.what = 100;
                }
                resultHandler.sendMessage(message);
            }
        }
    }

    /**
     * 群聊消息回调
     */
    @Override
    public void handleUnlimitGroupMsg(MsgData news){

    }

    public void updateProgress(int progress){
        System.out.println("进度："+progress);
        mResultProgress.setProgress(progress);
        if (progress == 100){
            mResultAdapter.notifyDataSetChanged();
            mResultProgress.setProgress(0);
        }
    }

    static class ResultHandler extends Handler {
        WeakReference<NewsFragment> fragmentRef;

        ResultHandler(NewsFragment activity) {
            fragmentRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            NewsFragment theActivity = fragmentRef.get();
            if (msg.what == 200) {
                MsgData msgData = (MsgData) msg.obj;
                if (null == msgData || msgData.getContent() == null || "".equals(msgData.getContent())) {
                    ToastUtil.showToast("无详情");
                    return;
                }
                Intent itemIntent = new Intent(theActivity.getActivity(), WebViewActivity.class);
                itemIntent.putExtra(WebViewActivity.key, msgData);
                theActivity.startActivity(itemIntent);
            } else {
                theActivity.updateProgress(msg.what);
            }
        }
    };
}
